import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { GridConfigService } from 'app/core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { Router } from '@angular/router';
import { ICellRendererParams } from '@ag-grid-community/core';
import { Events } from '@core/services/events/Events';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { DatePipe } from '@angular/common';
import { UserAuthService } from '@core/services/user-auth.service';
import * as CryptoJS from 'crypto-js';
import { BiService } from '../bi.service';
import {AllModules, Module} from "@ag-grid-enterprise/all-modules";

@Component({
  selector: 'car-info-details',
  templateUrl: './car-info-details.component.html',
  styleUrls: ['./car-info-details.component.scss'],
})
export class CarInfoDetailsComponent implements OnInit {
  modules: Module[] = AllModules;
  /* 按钮相关 */
  buttonBar = [{ hide: true, style: 'default', label: '查询', id: 'action_query', loading: false },
    { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
    { hide: true, style: 'default', label: '导出', id: 'action_export' },
    // {hide: false, style: 'default', label: '重置查询条件', id: 'action_reset'}
  ];
  title = '';
  ctx = { model: {} };
  hidn: any = 'none';

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules: any;
  getContextMenuItems: any;
  height: any = window.innerHeight - 325 + 'px';
  params: ICellRendererParams;

  /** 时间相关 **/
  mdjcTime: any = [];
  startValue: Date = null;
  endValue: Date = null;
  days: any;
  hind: any = 'none';    // 时间必填提示
  hindd: any = 'none';   // 收起查询条件
  yjjcTime: any = [];
  yjjcTime_ks = null;
  yjjcTime_js = null;

  checkOne: boolean;
  checkTwo: boolean;
  checkThe: boolean;
  checkFor: boolean;
  checkFro: boolean;

  // 获取门店
  nxmdList: any[];
  arrNXMD = [];
  ngNXMD: any;
  saleList: any [];
  sale = [];
  saleID: any [];

  fwlxList: any[];
  arrFWLX = [];
  ngFWLX: any;
  cphmName: string;
  ngJD: any;
  carBrands: string;

  btn: string = 'default';
  key: any;
  data: any;

  // 获取 查询头部
  queryList: any[];
  query: string = 'CarInStore';
  // 获取 车在哪
  carList: any[];
  carWhere = [];
  carID: any;
  // 获取 定损进度
  fixedList: any[];
  fixedLoss = [];
  fixedID: any;
  // 获取 年审进度
  annualList: any[];
  annualTrial = [];
  annualID: any;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId ; //this.userInfo.userAccount.post.company.id;
  companyData: any;
  companyList: any[];
  deptId: any;

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private router: Router, private event: Events,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private contextMenuService: ApesContextMenuService,
              private datePipe: DatePipe,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      { 'headerName': '门店', field: 'MDMC', width: 160 },
      { 'headerName': '接车人', field: 'JIECRMC', width: 120 },
      { 'headerName': '车牌', field: 'CPHM', width: 120 },
      { 'headerName': '厂牌', field: 'QCCPMC', width: 120 },
      { 'headerName': '项目', field: 'FWLXMC', width: 100 },
      { 'headerName': '总耗时', field: 'HJCS', width: 120, cellRenderer: this.toHour },
      { 'headerName': '车辆状态', field: 'JD', width: 120 },
      { 'headerName': '接车时间', field: 'JCRQ_SJ', width: 150 },
      { 'headerName': '预计交车时间', field: 'YJJCRQ_SJ', width: 150 },
      { 'headerName': '交车超时', field: 'JCBEYONDTIME', width: 120, cellRenderer: this.toHour, sort: 'desc' },
      { 'headerName': '水泡车', field: 'SPCBJ', width: 120 },
      { 'headerName': '车在哪', field: 'CARPLACEMC', width: 120 },
      { 'headerName': '钣喷进度', field: 'BPJDMC', width: 120 },
      { 'headerName': '配件进度', field: 'PJJDMC', width: 120 },
      { 'headerName': '节点耗时', field: 'JDHS', width: 120, cellRenderer: this.toHour },
      { 'headerName': '节点超时', field: 'JDCS', width: 120, cellRenderer: this.toHour },
      { 'headerName': '定损进度', field: 'DSJDMC', width: 120 },
      { 'headerName': '年审进度', field: 'NSJDMC', width: 120 },
      { 'headerName': '返修车', field: 'FXCMC', width: 120 },
      { 'headerName': '内协接车人', field: 'JDJIECR', width: 120 },
      { 'headerName': '内协接车时间', field: 'JDJCRQ_SJ', width: 150 },
      { 'headerName': '预计还车时间', field: 'JDYJJCRQ_SJ', width: 150 },
      { 'headerName': '实际还车时间', field: 'JDGHRQ_SJ', width: 150 },
      { 'headerName': '车型', field: 'CHXMC', width: 120 },
      { 'headerName': '销售组', field: 'XSZMC', width: 120 },
      { 'headerName': '实际交车时间', field: 'JCRQ_SJ_END', width: 150 },
      { 'headerName': '公司', field: 'COMPANYID', width: 150 },
    ];
    // if (this.userInfo.userAccount.post.branchObj !== undefined){
    //   this.companyId =this.userInfo.userAccount.post.branchObj.origin;
    // }else{
      this.companyId = this.userInfo.userAccount.post.company.id;
    // }
    this.companyList = [];
    this.companyList.push(this.companyId);
    this.getQueryHead(this.companyList);

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 50,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.rowClassRules = {
      // 预警
      'grid-tab-breach': function(params) {
        const YJJCSJ = params.data.YJJCRQ;
        const now = params.data.YJCS;
        const overTime = params.data.JDCS;
        if (now > 0 && overTime <= 0) {
          return (now > 0 && overTime <= 0);
        } else {
          return (YJJCSJ > -60 && YJJCSJ <= 0);
        }
      },
      // 超时
      'grid-tab-warning': function(params) {
        const YJJCSJ = params.data.YJJCRQ;
        const overTime = params.data.JDCS;
        if (overTime > 0) {
          return overTime > 0;
        } else {
          return YJJCSJ > 0;
        }
      },
    };
    this.getContextMenuItems = (params) => {
      const result = [
        'copy',
        'separator',
        { name: params.value },
        'separator',
        {
          name: '查看详情',
          action: () => {
            const dataModal = params.node.data;
            this.send(dataModal);
          },
        },
      ];
      return result;
    };
  }

  ngOnInit() {
    if (this.userInfo.userAccount.post.branchObj !== undefined) {
    //   if(this.userInfo.userAccount.post.dept !== undefined) {
    //   this.deptId = this.userInfo.userAccount.post.dept.id;
      this.ngNXMD = this.userInfo.userAccount.post.branchObj.origin;
      // this.ngNXMD = this.deptId;
    }
    if (this.userInfo.userAccount.post.dept !== undefined) {
      this.deptId = this.userInfo.userAccount.post.dept.id;
    }
    if(!this.deptId){
      this.ngNXMD = null;
    }


    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => {
      this.companyData = value;
    });
    this.queryData();
    this.getNxmdData();
    this.getFwjdData();
    this.getSaleData();
    this.getCarWhere();
    this.getFixedLoss();
    this.getAnnualTrial();

  }

  // 跳转详情页
  send(params: any) {
    this.data = params;
    // 加密传参
    let value = CryptoJS.enc.Utf8.parse(JSON.stringify(this.data));
    value = CryptoJS.enc.Base64.stringify(value);
    this.router.navigate(['/bi/car-info-details/carList/carListComponent'], { queryParams: { value: value } });
  }

  btnChange(key: any) {
    if (this.query === key) {
      this.query = undefined;
    } else {
      this.query = key;
    }
  }

  getTimeChang(d1, d2) {
    // debugger
    const day = 24 * 60 * 60 * 1000;
    try {
      const dateArr = d1.split('-');
      const checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      const checkTime = checkDate.getTime();

      const dateArr2 = d2.split('-');
      const checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      const checkTime2 = checkDate2.getTime();
      this.days = (checkTime - checkTime2) / day;
      // 判断 接车时间 和 交车时间 为一个月
      if (this.days <= 31) {
        return 'hide';
      } else {
        return 'show';
      }

    } catch (e) {
      return false;
    }
  }

  refresh(params: any): boolean {
    return undefined;
  }

  agInit(params: ICellRendererParams): void {
    this.params = params;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_show') {
        this.action_show();
      } else if (data.id === 'action_export') {
        this.action_export();
      }
    }
  }

  action_reset() {
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    for (let i = 0, len = this.rowData.length; i < len; i++) {
      this.rowData[i]['JDHS'] = this.showTime(this.rowData[i]['JDHS']);
      this.rowData[i]['JDCS'] = this.showTime(this.rowData[i]['JDCS']);
      this.rowData[i]['HJCS'] = this.showTime(this.rowData[i]['HJCS']);
      if (this.rowData[i]['DSBJ'] === 1) {
        this.rowData[i]['DSBJ'] = '√';
      }
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '在店车辆状况');
  }

  action_show() {
    if (this.hidn === 'none') {
      this.hidn = 'flex';
    } else if (this.hidn === 'flex') {
      this.hidn = 'none';
    }
  }

  queryData() {
    // if(this.companyList.length <= 0){
    //     this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.getDate(this.mdjcTime, 'startValue', 'endValue');
    this.getDate(this.yjjcTime, 'yjjcTime_ks', 'yjjcTime_js');
    if (this.checkFor === true) {
      this.query = undefined;
      if (this.mdjcTime.length === 0) {
        const endDates = new Date();
        const startDates = new Date(new Date().getTime() - (30 * 24 * 60 * 60 * 1000));
        const mdjcTimes = [];
        mdjcTimes.push(startDates);
        mdjcTimes.push(endDates);
        this.mdjcTime = mdjcTimes;
        //  控制接车时间 必填
        if (this.getTimeChang(this.endValue, this.startValue) === 'show') {
          this.hind = 'block';
        } else {
          this.hind = 'none';
        }
      }
      if (this.hind === 'block' || this.hindd === 'block') {
        this.buttonBar[0].loading = false;
      } else {
        this.getQueryHead(this.companyList);
        this.getTablesData();
      }
    } else {
      this.hidn = 'none';
      this.hind = 'none';
      this.hindd = 'none';
      this.getQueryHead(this.companyList);
      this.getTablesData();
    }

  }

  getDate(time: any[], time_ks: string, time_js: string) {
    const [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }
  }

  getTablesData() {
    let data = {};
    if (this.ngNXMD !== null && this.ngNXMD !== undefined) {
      data = {
        'interfaceMethod': 'ipmCLZKForAppService.getLeftTotal', 'pdata': {
          'JCSJSTART': this.startValue, 'JCSJEND': this.endValue,
          'GHSJSTART': this.yjjcTime_ks, 'GHSJEND': this.yjjcTime_js,
          'CPHM': this.cphmName, 'FWLX': this.ngFWLX, 'JD': this.ngJD,   // 车辆状态
          'MDID': this.ngNXMD, 'XSZID': this.saleID, 'SPCBJ': this.checkFro,
          'KEY': this.query,  // 头部
          'DSZT': this.checkOne,  // 定损车
          'FXCBJ': this.checkTwo,  // 返修车
          'NSCBJ': this.checkThe,   // 年审车
          'YJCZT': this.checkFor,   // 已交车
          'NSJDID': this.annualID,  // 年审进度
          'CARPLACEID': this.carID,  // 车在哪
          'DSJDID': this.fixedID,     // 定损进度
          'QCCPMC': this.carBrands,     // 汽车厂牌
        },
      };
    } else {
      data = {
        'interfaceMethod': 'ipmCLZKForAppService.getLeftTotal', 'pdata': {
          'JCSJSTART': this.startValue, 'JCSJEND': this.endValue,
          'GHSJSTART': this.yjjcTime_ks, 'GHSJEND': this.yjjcTime_js,
          'CPHM': this.cphmName, 'FWLX': this.ngFWLX, 'JD': this.ngJD,   // 车辆状态
          'MDID': this.ngNXMD, 'XSZID': this.saleID, 'SPCBJ': this.checkFro,
          'KEY': this.query,  // 头部
          'DSZT': this.checkOne,  // 定损车
          'FXCBJ': this.checkTwo,  // 返修车
          'NSCBJ': this.checkThe,   // 年审车
          'YJCZT': this.checkFor,   // 已交车
          'NSJDID': this.annualID,  // 年审进度
          'CARPLACEID': this.carID,  // 车在哪
          'DSJDID': this.fixedID,     // 定损进度
          'companyId': this.companyList,     // 公司
          'QCCPMC': this.carBrands,     // 汽车厂牌
        },
      };
    }

    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            const nowDate = new Date().getTime();
            for (let i = 0, len = data.length; i < len; i++) {
              if (data[i]['DSBJ'] === 1) {
                data[i]['DSBJ'] = '√';
              } else {
                data[i]['DSBJ'] = null;
              }
              if (data[i]['JDCS'] < 0) {
                data[i]['JDCS'] = null;
              }
              if (data[i]['YJJCRQ_SJ'] !== undefined) {
                data[i]['YJJCRQ'] = parseInt(((nowDate - new Date(data[i]['YJJCRQ_SJ']).getTime()) / 1000 / 60).toFixed());
              }
              data[i]['JDJCRQ_SJ'] = this.datePipe.transform(
                data[i]['JDJCRQ_SJ'], 'yyyy-MM-dd HH:mm:ss');
              data[i]['JDYJJCRQ_SJ'] = this.datePipe.transform(
                data[i]['JDYJJCRQ_SJ'], 'yyyy-MM-dd HH:mm:ss');
              data[i]['JDGHRQ_SJ'] = this.datePipe.transform(
                data[i]['JDGHRQ_SJ'], 'yyyy-MM-dd HH:mm:ss');
              data[i]['JCRQ_SJ_END'] = this.datePipe.transform(
                data[i]['JCRQ_SJ_END'], 'yyyy-MM-dd HH:mm:ss');
            }

            this.rowData = data;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
            this.buttonBar[0].loading = false;
          }
        } else {
          this.buttonBar[0].loading = false;
          this.msg.info(result.msg);
        }
      });
  }

  // 获取门店名称
  getNxmdData() {
    const data = { 'interfaceMethod': 'ipmBPforAppService.getSQMDXX', 'pdata': { 'companyId': this.companyList } };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.nxmdList = data;
            this.arrNXMD = this.nxmdList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取销售组
  getSaleData() {
    const data = {
      'interfaceMethod': 'ipmQueryXszService.queryXszData', 'pdata': { 'MJBJ': 0 },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.saleList = data;
            this.sale = this.saleList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取 服务节点
  getFwjdData() {
    const data = { 'interfaceMethod': 'ipmCLZKForAppService.getFWLX', 'pdata': {} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.fwlxList = data;
            this.arrFWLX = this.fwlxList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取 车在哪
  getCarWhere() {
    const data = { 'interfaceMethod': 'ipmCLZKForAppService.getCarPlace', 'pdata': {} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.carList = data;
            this.carWhere = this.carList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取 定损进度
  getFixedLoss() {
    const data = { 'interfaceMethod': 'ipmCLZKForAppService.getDsjd', 'pdata': {} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.fixedList = data;
            this.fixedLoss = this.fixedList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取 年审进度
  getAnnualTrial() {
    const data = { 'interfaceMethod': 'ipmCLZKForAppService.getNsjd', 'pdata': {} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.annualList = data;
            this.annualTrial = this.annualList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取 查询头部
  getQueryHead(company) {
    const data = { 'interfaceMethod': 'ipmCLZKForAppService.getClzkHead', 'pdata': { 'companyId': company } };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.queryList = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 节点
  arrJD = [
    { label: '检测中', key: 1 },
    { label: '定损中', key: 2 },
    { label: '待方案提交', key: 26 },
    { label: '待配件报价', key: 21 },
    { label: '待技术审核', key: 20 },
    { label: '待价格审核', key: 22 },
    { label: '待方案确认', key: 3 },
    { label: '等货中', key: 4 },
    // {label: "基地等货中", key: 5},
    { label: '待施工', key: 6 },
    // {label: "基地待施工", key: 7},
    { label: '待基地接车', key: 8 },
    // {label: "施工暂停", key: 27},
    // {label: "本店施工中", key: 10},
    { label: '施工中', key: 9 },
    { label: '待外协派工', key: 23 },
    { label: '外协施工中', key: 24 },
    { label: '待基地还车', key: 11 },
    { label: '待质检', key: 12 },
    { label: '待收款', key: 13 },
    { label: '待催款', key: 19 },
    { label: '待交车', key: 14 },
    { label: '待到店施工', key: 17 },
    // {label: "待到店施工，货已到", key: 18},
    { label: '年审中', key: 25 },
    { label: '拆检中', key: 29 },
    { label: '待门店收车', key: 28 },
    { label: '未结算交车', key: 30 },
    { label: '待复勘', key: 35 },
    { label: '待调查', key: 36 },
    { label: '未年审', key: 37 },
    { label: '冷门车', key: 38 },
    { label: '无车损', key: 39 },
    { label: '待报废', key: 40 },
    { label: '待验件', key: 41 },
    { label: '需外出定损', key: 42 },
    { label: '待上门定损', key: 43 },
    { label: '评估中', key: 44 },
    { label: '待重开案', key: 45 },
  ];

  // 时间转换（配合grid调用）
  toHour(params) {
    const key = params.colDef.field;
    const data = params.data[key];
    const day = Math.floor(data / (24 * 60));
    const hour = day >= 0
      ? Math.floor((data - (day * (24 * 60))) / 60)
      : Math.floor(data / 60);
    const minute = hour >= 0
      ? Math.floor(data - (day * (24 * 60)) - (hour * 60))
      : data < 0
        ? data
        : Math.floor(data / 60 / 24);

    let times = '';
    if (day > 0) {
      times = day + '天' + hour + '小时';
    } else if (hour) {
      times = hour + '小时' + minute + '分钟';
    } else if (minute) {
      times = minute + '分钟';
    }
    return times;
  }

  // 时间转换 （导出时调用转换）
  showTime(data) {
    const day = Math.floor(data / (24 * 60));
    const hour = day >= 0
      ? Math.floor((data - (day * (24 * 60))) / 60)
      : Math.floor(data / 60);
    const minute = hour >= 0
      ? Math.floor(data - (day * (24 * 60)) - (hour * 60))
      : data < 0
        ? data
        : Math.floor(data / 60 / 24);

    let times = '';
    if (day > 0) {
      times = day + '天' + hour + '小时';
    } else if (hour) {
      times = hour + '小时' + minute + '分钟';
    } else if (minute) {
      times = minute + '分钟';
    }
    return times;
  }

  // 排序 倒序
  sortarr(key) {
    return function(a, b) {
      a[key] === undefined ? a[key] = 0 :
        b[key] === undefined ? b[key] = 0 : 0;
      return b[key] - a[key];
    };
  }

}
